/**
 * dev=http://192.168.5.245:8099/XHSCAdminServer
 * test=http://192.168.0.232:8088/XHSCAdminServer
 * **/

var Doman = {
    // url:"http://iscadmin.yunzuoye.net/XHSCAdminServer",
    //url:"http://192.168.8.41:9002/XHSCAdminServer",
    // url:"http://192.168.5.60:9002/XHSCAdminServer",
    // url:"http://192.168.8.41:9002/XHSCAdminServer",
    dataCenterUrl:"https://isdc.yunzuoye.net/XHDataCenter",
    url:window.top.xhTop.getConfigByName('fInSchool').url,
    courseList: "/course/ware/list",
    courseDelete: "/course/ware/revocation",
    pptDelete: "/course/ware/ppt/delete",
    courseWareSave: "/course/ware/save",
    courseWareDelete:"/course/ware/delete",
    topicList: "/topic/list",
    topicRevocation: "/topic/revocation",
    topicCombine: "/topic/combine",
    topicDetailList: "/topic/detail/list",
    topicSplit: "/topic/split",
    topicIdGet: "/topic/id/get",
    topicSort: "/topic/sort",
    courseSelflist: "/course/selflist",
    unitSelflist: "/unit/selflist",
    courseDetail: "/course/detail",
    topicImport: "/topic/import",
    courseWareImport: "/course/ware/import",
    courseWareDoc: "/course/ware/doc",
    courseUpdateDes: "/course/ware/update/description",//更新描述
    topicUpdateDes: "/topic/update/description",//更新描述
    topicGroupRevocation: "/topic/group/revocation",
    topicSave: "/topic/save",
    topicGroupSave: "/topic/group/save",
    topicUpdate: "/topic/update",
    courseDoc: '/course/ware/doc',
    courseWareUpdate: '/course/ware/update',
    sontopicSave: '/sontopic/save',
    sontopicRevocation: '/sontopic/revocation',
    sontopicSort: '/sontopic/sort',
    periodGetAll: '/period/getAll',
    periodInfoGet: '/api/v1/user/periodInfo/get',
    xnPeriodInfoGet: '/user/periodInfo/get',
    periodInfoSave: '/api/v1/user/periodInfo/save',
    xnPeriodInfoSave: '/user/periodInfo/save',
    addBelong: '/add/belong',
    addEdition: '/add/edition',
    addPeriod: '/add/period',
    addSubject: '/add/subject',
    alterBelong: '/alter/belong',
    alterEdition: '/alter/edition',
    alterPeriod: '/alter/period',
    alterSubject: '/alter/subject',
    deleteBelong: '/delete/belong',
    deleteEdition: '/delete/edition',
    deletePeriod: '/delete/period',
    deleteSubject: '/delete/subject',
    outCourseList: '/out/course/list',
    outUnitList: '/out/unit/list',
    outWareImport: '/out/ware/import',
    outTopicList: '/out/topic/list',
    outTopicImport: '/out/topic/import',
    //资源请求接口
    getUserInfo:'/api/v1/get/user/info',
    getPage:'/api/v1/resource/get/page',
    resourceDelete:'/api/v1/resource/delete',
    batchDownload:'/api/v1/batch/download',
    alterInfo:'/api/v1/resource/alter/info',
    resourceSave:'/api/v1/resource/save',
    resourceAlterSubject: '/api/v1/resource/alter/subject',
    alterAuth: '/api/v1/resource/alter/auth',
    resourceDump: '/api/v1/resource/dump',
    searchSchool: '/api/v1/search/school'

};

var SystemConfig = {
    appKey: "CA102001",
    fileUploadUrl: "https://filesoss.yunzuoye.net/XHFileServer/file/upload/",
    fileMd5: "292D078A1080533587F7F968803C0483",
    openPlayView:"https://play.yunzuoye.net/play?src="
};

/**
 * 用户信息
 */
var User = {
    token:getUserId(),
    // token: "27330",
    timeStamp: new Date().getTime()
};
var Complete = 0;
var dataLength = 0;

//将文件名转换为md5格式
//function doNormalTest(_url,_fileElementId,_complete) {
//    var fileReader = new FileReader(),
//        file = document.getElementById(_fileElementId).files[0];
//    fileReader.onload = function (e) {
//        if (file.size = e.target.result.length) {
//            md5 = SparkMD5.hashBinary(e.target.result).toUpperCase();
//            ajaxFileUpload(_url+md5,_fileElementId,file,_complete);
//        }
//    };
//    fileReader.readAsBinaryString(file);
//}
function doNormalTest(_url, _fileElementId) {
    var fileReader = new FileReader(),
        file = document.getElementById(_fileElementId).files[0];
    fileReader.onload = function (e) {
        if (file.size = e.target.result.length) {
            md5 = SparkMD5.hashBinary(e.target.result).toUpperCase();
            ajaxFileUpload(_url + md5, _fileElementId, file, _complete);
        }
    };
    fileReader.readAsBinaryString(file);
}

//将文件名转换为md5格式(标)
function filenameMd5(_url, _fileElementId) {
    var md5 = "";
    var fileReader = new FileReader();
    file = document.getElementById(_fileElementId).files[0];
    fileReader.onload = function(e) {
        if (file.size = e.target.result.byteLength) {
            var bytes = new Uint8Array(fileReader.result);
            var length = bytes.byteLength;
            var binary = '';
            for (var i = 0; i < length; i++) {
                binary += String.fromCharCode(bytes[i]);
            }
            md5 = SparkMD5.hashBinary(binary).toUpperCase();
            fileUpload(_url + md5, _fileElementId, file);
        }
    };
    fileReader.readAsArrayBuffer(file);
}


//将文件名转换为md5格式
function filenameMd5x(_url, _fileElementId) {
    var fileReader = new FileReader(),
        file = document.getElementById(_fileElementId).files[0];
    fileReader.onload = function (e) {
        if (file.size = e.target.result.length) {
            md5 = SparkMD5.hashBinary(e.target.result).toUpperCase();
            fileUploadx(_url + md5, _fileElementId, file);
        }
    };
    fileReader.readAsBinaryString(file);
}
//异步提交文件(标)
function fileUpload(_url, _fileElementId, formObj) {
    /* FormData 是表单数据类 */
    var fd = new FormData();
    var ajax = new XMLHttpRequest();
    /* 把文件添加到表单里 */
    fd.append("files", formObj);
    ajax.open("post", _url, true);
    ajax.onload = function () {
        var result = JSON.parse(ajax.responseText).uploadFileDTO.fileId;
        if (JSON.parse(ajax.responseText).status == "1000") {
            document.getElementById(_fileElementId).nextElementSibling.value = result;
            document.getElementById(_fileElementId).parentNode.parentNode.nextElementSibling.innerHTML = document.getElementById(_fileElementId).value;
            document.getElementById(_fileElementId).parentNode.parentNode.nextElementSibling.nextElementSibling.style.display = "inline-block";
        }
    };
    ajax.send(fd);
    return false;
}


//异步提交文件
function fileUploadx(_url, _fileElementId, formObj) {
    /* FormData 是表单数据类 */
    var fd = new FormData();
    var ajax = new XMLHttpRequest();
    /* 把文件添加到表单里 */
    fd.append("files", formObj);
    ajax.open("post", _url, false);
    ajax.onload = function () {
        var result = JSON.parse(ajax.responseText).uploadFileDTO.fileId;
        if (JSON.parse(ajax.responseText).status == "1000") {
            document.getElementById(_fileElementId).nextElementSibling.value = result;
            var reader = new FileReader();
            reader.readAsDataURL(formObj);
            reader.onload = function(e){
                innerPic(this.result,result);
            }
            //innerPic(result);
        }
    };
    ajax.send(fd);
    document.getElementById("myForm").reset();
    return false;
}
//异步提交doc ppt cwep md5文件
function ajaxFileUpload(_url, _fileElementId, formObj, _complete) {
    /* FormData 是表单数据类 */
    var fd = new FormData();
    var ajax = new XMLHttpRequest();
    /* 把文件添加到表单里 */
    fd.append("files", formObj);
    ajax.open("post", _url, true);
    ajax.onload = function () {
        var result = JSON.parse(ajax.responseText).uploadFileDTO.fileId;
        document.getElementById(_fileElementId).nextElementSibling.value = result;
        if (JSON.parse(ajax.responseText).status == "1000") {
            Complete += parseInt(_complete);
            if (Complete == "100") {
                var courseSave = {
                    "attachmentUrl": $("#ppt_result").val(),
                    "fileUrl": $("#cwep_result").val(),
                    //"fileUrl": "",
                    "courseWareId": 0,
                    "fileLength": 0,
                    "isRecord": 2,
                    "session": "string",
                    "token": User.token,
                    "timeStamp": User.timeStamp
                }
                courseSave = JSON.stringify(courseSave);
                console.log(courseSave)
                //保存课件
                $.ajax({
                    type: 'POST',  //POST/PUT/DELETE/HEAD
                    url: Doman.url + Doman.courseSave,
                    contentType: "application/json",
                    data: courseSave,
                    success: function (data) {
                        $("#CreateCourse_wait").css('display', 'none');
                        $("#CreateCourse").css('display', 'none');
                        window.location.reload(true);
                    },	//成功响应的回调
                    error: function () {
                        console.log("error");
                    }		//失败响应的回调
                });
            }
        }
    };
    ajax.send(fd);
    return false;
}

function openUrl(_locationHref, _html, _title) {
    //window.open("./TopicManageDetail.html");
    var arr;
    var str;
    if(_locationHref.indexOf("https://")==-1){
        arr = _locationHref.split('http://')[1].split('/');
        str = "http://";
    }else{
        arr = _locationHref.split('https://')[1].split('/');
        str = "https://";
    }

    for (var i = 0; i < arr.length - 1; i++) {
        str += arr[i] + "/"
    }
    str += _html;
    if (window.top.xhTop) {
        window.top.xhTop.createNewTab(_title, str, true);
    } else {
        window.location.href = str;
    }
}

function Dlog(log) {
    console.log(log)
}

function getCookie(c_name)
{
    if (document.cookie.length>0)
    {
        c_start=document.cookie.indexOf(c_name + "=")
        if (c_start!=-1)
        {
            c_start=c_start + c_name.length+1
            c_end=document.cookie.indexOf(";",c_start)
            if (c_end==-1) c_end=document.cookie.length
            return unescape(document.cookie.substring(c_start,c_end))
        }
    }
    return ""
}
/**
 * 获取用户ID
 */
function getUserId() {
    var userInfo = JSON.parse(getCookie("userInfo"));
    return userInfo.UserId;
}
//*****************************************************华丽分割线*********************************************************** */

//异步提交文件
function uploadFile(_url, formObj, callback) {
    getFileMd5(formObj, function (md5) {
        /* FormData 是表单数据类 */
        var fd = new FormData();
        var ajax = new XMLHttpRequest();
        /* 把文件添加到表单里 */
        fd.append("files", formObj);
        ajax.open("post", _url + md5, true);
        ajax.setRequestHeader("XueHai-MD5",md5);
        ajax.onload = function () {
            var result = JSON.parse(ajax.responseText).uploadFileDTO.fileId;
            if (JSON.parse(ajax.responseText).status == "1000") {
                callback(ajax.responseText);
            } else {
                //返回失败
                callback('{status:2000,message:"失败了!"}');
            }
            $(".wait").css("display", "none");
        };
        ajax.send(fd);
    });

}


//将文件名转换为md5格式
function getFileMd5(file, callback) {
    var md5 = "";
    var fileReader = new FileReader();
    fileReader.onload = function(e) {
        if (file.size = e.target.result.byteLength) {
            var bytes = new Uint8Array(fileReader.result);
            var length = bytes.byteLength;
            var binary = '';
            for (var i = 0; i < length; i++) {
                binary += String.fromCharCode(bytes[i]);
            }
            md5 = SparkMD5.hashBinary(binary).toUpperCase();
            callback(md5);
        }
    };
    fileReader.readAsArrayBuffer(file);
}

/**
 * 删除操作
 * @param {*请求url} url
 * @param {*是否同步} sync
 * @param {*数据对象} form
 * @param {*回调} callback
 */
function getObject(url, sync, form, callback) {
    $.ajax({
        type: "get",
        url: url,
        data: form,
        async:sync,
        dataType: "json",
        contentType:"application/json",
        success: function (result) {
            callback(result)
        }
    });
}
/**
 * 删除操作
 * @param {*请求url} url
 * @param {*是否同步} sync
 * @param {*数据对象} form
 * @param {*回调} callback
 */
function delObject(url, sync, form, callback) {
    $.ajax({
        type: "delete",
        url: url,
        data: form,
        dataType: "json",
        contentType:"application/json",
        success: function (result) {
            callback(result)
        }
    });
}
/**
 * 保存操作
 * @param {*请求url} url
 * @param {*是否同步} sync
 * @param {*数据对象} form
 * @param {*回调} callback
 */
function saveObject(url, sync, form, callback,callbackError) {
    $.ajax({
        type: "put",
        url: url,
        data: form,
        async:sync,
        dataType: "json",
        contentType:"application/json",
        success: function (result) {
            callback(result)
        },
        error:function(result){
            callbackError(result)
        }
    });
}
/**
 * 更新操作
 * @param {*请求url} url
 * @param {*是否同步} sync
 * @param {*数据对象} form
 * @param {*回调} callback
 */
function updateObject(url, sync, form, callback,errorCallback) {
    $.ajax({
        type: "POST",
        url: url,
        data: form,
        async:sync,
        dataType: "json",
        contentType:"application/json",
        success: function (result) {
            callback(result)
        },
        error:function(result){
            errorCallback(result)
        }
    });
}
/**
 * 公共弹框
 * @param {*弹框样式} type
 * @param {*提示内容} val
 */
function tip(type, val) {
    //TODO 实现
    console.log("请先实现Tip方法！");
}
//刷新当前页面
function refresh(){
    var page=$("#pageToolbar .focus").attr("data-page")-1;
    var pageSize=$("#pageToolbar").attr("pageSize");
    manageList(page,pageSize);
    $('body').css({"overflow":"scroll"});
}
function getParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null)return unescape(r[2]);
    return null;
}
/**
 * 转换时长 2'22''
 */
function changeTime(time){
    var minute=parseInt(time/60);
    var second=time%60;
    if(minute==0){
        return second+"''"
    }else{
        return minute+"'"+second+"''"
    }
}
/**
 * 转换时间 20xx-xx-xx xx:xx:xx
 */
function changeDate(time){
    var DateMonth = new Date(time).getMonth() + 1;
    if (DateMonth < 10) {
        DateMonth = '0' + DateMonth;
    }
    var DateDay = new Date(time).getDate();
    if (DateDay < 10) {
        DateDay = '0' + DateDay;
    }
    var DateHour = new Date(time).getHours();
    if (DateHour < 10) {
        DateHour = '0' + DateHour;
    }
    var DateMinutes = new Date(time).getMinutes();
    if (DateMinutes < 10) {
        DateMinutes = '0' + DateMinutes;
    }
    var DateSeconds = new Date(time).getSeconds();
    if (DateSeconds < 10) {
        DateSeconds = '0' + DateSeconds;
    }
    return (new Date(time).getFullYear()) + '-' + DateMonth + '-' + DateDay + '&nbsp;' + DateHour + ':' + DateMinutes + ':' + DateSeconds
}
/**
 * 修改地址栏
 * @param {*目标字符串，比如是http://www.huistd.com/?id=3&ttt=3 } destiny
 * @param {*参数名} par
 * @param {*参数要更改的值} par_value
 */
function changeURLPar(destiny, par, par_value) {
    var pattern = par + '=([^&]*)';
    var replaceText = par + '=' + par_value;
    if (destiny.match(pattern)) {
        var tmp = '/\\' + par + '=[^&]*/';
        tmp = destiny.replace(eval(tmp), replaceText);
        return (tmp);
    }
    else {
        if (destiny.match('[\?]')) {
            return destiny + '&' + replaceText;
        }
        else {
            return destiny + '?' + replaceText;
        }
    }
    return destiny + '\n' + par + '\n' + par_value;
}

/**
 * 限制字段
 */
$.fn.wordLimit = function(num){
    this.each(function(){
        if(!num){
            var copyThis = $(this.cloneNode(true)).hide().css({
                'position': 'absolute',
                'width': 'auto',
                'overflow': 'visible'
            });
            $(this).after(copyThis);
            if(copyThis.width()>$(this).width()){
                $(this).text($(this).text().substring(0,$(this).text().length-4));
                $(this).html($(this).html()+'...');
                copyThis.remove();
                $(this).wordLimit();
            }else{
                copyThis.remove(); //娓呴櫎澶嶅埗
                return;
            }
        }else{
            var maxwidth=num;
            if($(this).text().length>maxwidth){
                $(this).text($(this).text().substring(0,maxwidth));
                $(this).html($(this).html()+'...');
            }
        }
    });
};